/*
 * timestamp.cpp
 *
 *  Created on: 2008-9-5
 *      Author: fanliangliang
 */

#include "timestamp.h"
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sstream>

BEGIN_NAMESPACE_TOXIC

using namespace std;

Timestamp Timestamp::_startTime;

Timestamp::Timestamp(time_t seconds /*= 0*/)
:_time(0) {
	if (seconds == 0) {
		seconds = ::time(0);
	}
	struct tm* ptm = localtime(&seconds);
	setYear(ptm->tm_year + 1900);
	setMonth(ptm->tm_mon + 1);
	setDay(ptm->tm_mday);
	setHour(ptm->tm_hour);
	setMinute(ptm->tm_min);
	setSecond(ptm->tm_sec);
}

Timestamp::Timestamp(const string& str)
:_time(0) {
	istringstream strm(str);
	int data[6] = { 0 };
	for (int i = 0; i < 6; ++i) {
		strm >> data[i];
		strm.ignore();
	}

	setYear(data[0]);
	setMonth(data[1]);
	setDay(data[2]);
	setHour(data[3]);
	setMinute(data[4]);
	setSecond(data[5]);
}

Timestamp::~Timestamp() {

}

int Timestamp::time() const {
	return _time;
}

int Timestamp::year() const {
	return ((_time >> 26) & 0x3F) + 1970;
}

int Timestamp::month() const {
	return (_time >> 22) & 0x0F;
}

int Timestamp::day() const {
	return (_time >> 17) & 0x1F;
}

int Timestamp::hour() const {
	return (_time >> 12) & 0x1F;
}

int Timestamp::minute() const {
	return (_time >> 6) & 0x3F;
}

int Timestamp::second() const {
	return _time & 0x3F;
}

void Timestamp::setTime(int time) {
	_time = time;
}

void Timestamp::setYear(int year) {
	year -= 1970;
	_time &= 0x03FFFFFF;
	_time |= (year & 0x3F) << 26;
}

void Timestamp::setMonth(int month) {
	_time &= 0xFC3FFFFF;
	_time |= (month & 0x0F) << 22;
}

void Timestamp::setDay(int day) {
	_time &= 0xFFC3FFFF;
	_time |= (day & 0x1F) << 17;
}

void Timestamp::setHour(int hour) {
	_time &= 0xFFFE0FFF;
	_time |= (hour & 0x1F) << 12;
}

void Timestamp::setMinute(int minute) {
	_time &= 0xFFFFF03F;
	_time |= (minute & 0x3F) << 6;
}

void Timestamp::setSecond(int second) {
	_time &= 0xFFFFFFC0;
	_time |= second & 0x3F;
}
/*
static char* formatTime(const Timestamp& ts) {
	static char buf[20] = { 0 };
	snprintf(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d",
			ts.year(), ts.month(), ts.day(),
			ts.hour(), ts.minute(), ts.second());
	return buf;
}

string Timestamp::str() const {
	return formatTime(*this);
}
*/
string Timestamp::toString(const char* format /*= "%Y-%m-%d %H:%M:%S"*/) const {
	char buf[1024] = { 0 };
	struct tm t;
	t.tm_year = year() - 1900;
	t.tm_mon = month() - 1;
	t.tm_mday = day();
	t.tm_hour = hour();
	t.tm_min = minute();
	t.tm_sec = second();
	mktime(&t);
	size_t len = strftime(buf, 1024, format, &t);
	return len == 0 ? "" : buf;
}

Timestamp Timestamp::startTime() {
	return _startTime;
}

END_NAMESPACE_TOXIC
